package com.gyt.manager.common.component;

import com.gyt.manager.common.properties.LogProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * description.
 *
 * @author gyt create on 2021/6/2 16:03
 */
@Component
@Slf4j
public class LogComponent {

    private static final String DEFAULTCHART = "UTF-8";
    @Autowired
    private LogProperties logProperties;

    private Connection conn;

    /**
     * 远程登录linux的主机
     *
     * @return 登录成功返回true，否则返回false
     * @author Ickes
     * @since V0.1
     */
    public Boolean login() {
        boolean flag = false;
        try {
            //连接
            conn = new Connection(logProperties.getIp());
            conn.connect();
            //认证
            flag = conn.authenticateWithPassword(
                    logProperties.getUsername(), logProperties.getPassword());
        } catch (Exception e) {
            log.error("connection.linux.failed", e);
        }
        return flag;
    }

    /**
     * @param cmd 即将执行的命令
     * @return 命令执行成功后返回的结果值，如果命令执行失败，返回空字符串，不是null
     * @author Ickes
     * 远程执行shll脚本或者命令
     * @since V0.1
     */
    public String executeSuccess(String cmd) {
        String result = "";
        try {
            if (login()) {
                //打开一个会话
                Session session = conn.openSession();
                //执行命令
                session.execCommand(cmd);
                result = processStdoutSuccess(session.getStdout(), DEFAULTCHART);
                conn.close();
                session.close();
            }
        } catch (IOException e) {
            log.error("executeSuccess.error->", e);
        }
        return result;
    }

    /**
     * 解析脚本执行返回的结果集
     *
     * @param in      输入流对象
     * @param charset 编码
     * @return 以纯文本的格式返回
     * @author Ickes
     * @since V0.1
     */
    private String processStdoutSuccess(InputStream in, String charset) {
        InputStream stdout = new StreamGobbler(in);
        StringBuffer buffer = new StringBuffer();
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(stdout, charset));
            String line;
            while ((line = br.readLine()) != null) {
                buffer.append(line + "\n");
            }
        } catch (Exception e) {
            log.error("processStdoutSuccess.error->", e);
        }
        return buffer.toString();
    }

}
